package com.joysuch.wwyt.attendant.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.joysuch.wwyt.attendant.bean.AttendantStatisticsSearchBean;
import com.joysuch.wwyt.attendant.bean.vo.AttendantStatisticsAreaVo;
import com.joysuch.wwyt.attendant.bean.vo.AttendantStatisticsScreenVo;
import com.joysuch.wwyt.attendant.bean.vo.AttendantStatisticsUserVo;
import com.joysuch.wwyt.attendant.enums.AttendantStateEnum;
import com.joysuch.wwyt.attendant.enums.ProcessStatusEnum;
import com.joysuch.wwyt.attendant.service.AttendantAreaService;
import com.joysuch.wwyt.attendant.service.AttendantPlanService;
import com.joysuch.wwyt.attendant.service.AttendantRecordProcessService;
import com.joysuch.wwyt.attendant.service.AttendantStatisticsService;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import com.joysuch.wwyt.core.repository.BaseUserDao;
import com.joysuch.wwyt.core.support.Context;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description //TODO
 * @Date 2023/2/17 17:33
 * @Author Leong
 **/
@Service
@Transactional(rollbackFor = Exception.class)
public class AttendantStatisticsServiceImpl implements AttendantStatisticsService {

    @Resource
    private BaseUserDao baseUserDao;

    @Resource
    private AttendantPlanService attendantPlanService;

    @Resource
    private AttendantRecordProcessService attendantRecordProcessService;

    @Resource
    private AttendantAreaService attendantAreaService;

    @Override
    public ResultBean findPersonPage(AttendantStatisticsSearchBean searchBean) {
        List<AttendantStatisticsUserVo> voList = new ArrayList<>();
        List<Long> userIds = new ArrayList<>();
        Page<AttendantStatisticsUserVo> page = new Page<>(searchBean.getPage() + 1, searchBean.getSize());
        if (StringUtils.isNotBlank(searchBean.getUserName())) {
            userIds = baseUserDao.findIdsByRealName(searchBean.getUserName());
            if (CollectionUtils.isEmpty(userIds)) {
                return ResultBean.pageData(voList, 0);
            }
        }
//        if (searchBean.getJobId() != null) {
//            List<Long> jobUserIds = baseUserDao.findAllUserByJob(searchBean.getJobId());
//            if (CollectionUtils.isEmpty(jobUserIds)) {
//                return ResultBean.pageData(voList, 0);
//            }
//            userIds.addAll(jobUserIds);
//        }
        userIds = userIds.stream().distinct().collect(Collectors.toList());
        Page<AttendantStatisticsUserVo> pageData = attendantPlanService.findStatisticsUserPage(page, userIds,searchBean.getJobId() ,searchBean.getWay(),searchBean.getStartTime(),searchBean.getEndTime(), Context.getCompanyCode(), Context.getCurrentTenantId());
        List<AttendantStatisticsUserVo> records = pageData.getRecords();
        if (!CollectionUtils.isEmpty(records)){
            Map<Long,AttendantStatisticsUserVo> userVoMap = new HashMap<>();
            userVoMap = records.stream().collect(Collectors.toMap(AttendantStatisticsUserVo::getUserId, e -> e));
            List<Long> recordUserIds = records.stream().map(AttendantStatisticsUserVo::getUserId).collect(Collectors.toList());
            //查询隐患数量
            List<AttendantStatisticsUserVo> vos = attendantRecordProcessService.findStatisticsUserList(recordUserIds);
            if (!CollectionUtils.isEmpty(vos)){
                for (AttendantStatisticsUserVo v : vos){
                    AttendantStatisticsUserVo userVo = userVoMap.get(v.getUserId());
                    if (userVo != null){
                        userVo.setHdFinishNum(v.getHdFinishNum());
                        userVo.setHdTotalNum(v.getHdTotalNum());
                    }
                }
            }
            for (AttendantStatisticsUserVo record : records) {
                //完成率
                if (record.getFinishNum() != null && record.getTaskNum() != null){
                    record.setFinishRate(BigDecimal.valueOf(record.getFinishNum()).divide(BigDecimal.valueOf(record.getTaskNum()),4, RoundingMode.HALF_DOWN));
                }
                if (record.getHdFinishNum() != null && record.getHdTotalNum() != null && record.getHdTotalNum() != 0){
                    record.setHdFinishRate(BigDecimal.valueOf(record.getHdFinishNum()).divide(BigDecimal.valueOf(record.getHdTotalNum()),4, RoundingMode.HALF_DOWN));
                }
            }
        }
        return ResultBean.pageData(records, page.getTotal());
    }

    @Override
    public ResultBean findAreaPage(AttendantStatisticsSearchBean searchBean) {
        List<AttendantStatisticsAreaVo> voList = new ArrayList<>();
        List<Long> areaIds = new ArrayList<>();
        Page<AttendantStatisticsAreaVo> page = new Page<>(searchBean.getPage() + 1, searchBean.getSize());
        if (StringUtils.isNotBlank(searchBean.getAreaName())) {
            areaIds = attendantAreaService.selectByName(searchBean.getAreaName());
            if (CollectionUtils.isEmpty(areaIds)) {
                return ResultBean.pageData(voList, 0);
            }
        }
        Page<AttendantStatisticsAreaVo> pageData = attendantPlanService.findStatisticsAreaPage(page, areaIds, searchBean.getWay(),searchBean.getStartTime(),searchBean.getEndTime(), Context.getCompanyCode(), Context.getCurrentTenantId());
        List<AttendantStatisticsAreaVo> records = pageData.getRecords();
        if (!CollectionUtils.isEmpty(records)){
            Map<Long,AttendantStatisticsAreaVo> areaVoMap = new HashMap<>();
            areaVoMap = records.stream().collect(Collectors.toMap(AttendantStatisticsAreaVo::getAreaId, e -> e));
            List<Long> recordAreaIds = records.stream().map(AttendantStatisticsAreaVo::getAreaId).collect(Collectors.toList());
            //查询隐患数量
            List<AttendantStatisticsAreaVo> vos = attendantRecordProcessService.findStatisticsAreaList(recordAreaIds);
            if (!CollectionUtils.isEmpty(vos)){
                for (AttendantStatisticsAreaVo v : vos){
                    AttendantStatisticsAreaVo areaVo = areaVoMap.get(v.getAreaId());
                    if (areaVo != null){
                        areaVo.setHdFinishNum(v.getHdFinishNum());
                        areaVo.setHdTotalNum(v.getHdTotalNum());
                    }
                }
            }
            for (AttendantStatisticsAreaVo record : records) {
                //完成率
                if (record.getFinishNum() != null && record.getTaskNum() != null){
                    record.setFinishRate(BigDecimal.valueOf(record.getFinishNum()).divide(BigDecimal.valueOf(record.getTaskNum()),4, RoundingMode.HALF_DOWN));
                }
                if (record.getHdFinishNum() != null && record.getHdTotalNum() != null){
                    record.setHdFinishRate(BigDecimal.valueOf(record.getHdFinishNum()).divide(BigDecimal.valueOf(record.getHdTotalNum()),4, RoundingMode.HALF_DOWN));
                }
                if (record.getHdTotalNum()==null) {
                    record.setHdTotalNum(0);
                    record.setHdFinishNum(0);
                    record.setHdFinishRate(BigDecimal.ZERO);
                }
            }
        }
        return ResultBean.pageData(records, page.getTotal());
    }

    @Override
    public AttendantStatisticsScreenVo findScreen() {
        AttendantStatisticsScreenVo vo = new AttendantStatisticsScreenVo();
        //总数
        long totalCount = attendantPlanService.countByStatus(null);
        //完成数量
        long finishCount = attendantPlanService.countByStatus(AttendantStateEnum.COMPLETED.getValue());
        //提交隐患数量
        long totalHdCount = attendantRecordProcessService.countByStatus(null);
        //隐患完成数
        long finishHdCount = attendantRecordProcessService.countByStatus(ProcessStatusEnum.FINISHED.getValue());
        vo.setTaskNum(totalCount);
        vo.setFinishNum(finishCount);
        if (finishCount>0){
            vo.setFinishRate(BigDecimal.valueOf(finishCount).divide(BigDecimal.valueOf(totalCount),4, RoundingMode.HALF_DOWN));
        }else {
            vo.setFinishRate(BigDecimal.ZERO);
        }
        vo.setHdTotalNum(totalHdCount);
        vo.setHdFinishNum(finishHdCount);
        if (totalHdCount>0) {
            vo.setHdFinishRate(BigDecimal.valueOf(finishHdCount).divide(BigDecimal.valueOf(totalHdCount),4, RoundingMode.HALF_DOWN));
        }else {
            vo.setHdFinishRate(BigDecimal.ZERO);
        }
        return vo;
    }
}
